import initRequest from './request'
import { useAuthStore } from '@/stores/modules/auth.js'
import { ElMessage } from 'element-plus'
import { ResultEnum } from '@/enums/httpEnum';
import { debounce } from 'xe-utils';

const messageDebounce = debounce(msg => ElMessage.warning(msg), 1500)

/**默认请求工具 */
const defaultUrl = import.meta.env.VITE_APP_BACKEND_ORIGIN + import.meta.env.VITE_APP_PREFIX_API
export const http = initRequest({
  baseUrl: defaultUrl,
  responseHook: (response) => {
    // 未登录前往登录页面
    if ((response.data.isError || response.data.IsError) && (response.data.message == '未登录' || response.data.Message == '未登录')) {
      const authStore = useAuthStore()
      authStore.cleanAuthInfo()
      /* window.open(response.data.Result, '_self') */
      authStore.toLoginPage()
      return 
    }
    if (response.status != 200) {
      ElMessage.error('请求失败')
    }
    return response.data
  },
  responseErrorHook: (error) => {
    if (error.response.status == ResultEnum.BAD_REQUEST && error.config.url != '/Achievements/GetAchievementsList') {
      messageDebounce('系统出现错误，请稍后重试')
    }
    return Promise.reject(error)
  }
})

/**调取用户信息工具 */
const authtUrl = import.meta.env.PROD ? import.meta.env.VITE_APP_BACKEND_ORIGIN : ''
export const authHttp = initRequest({
  baseUrl: authtUrl
})


/**调取用户信息工具 */
const userUrl = import.meta.env.PROD ? import.meta.env.VITE_APP_AUTH_ORIGIN : '/devAuth'
export const userHttp = initRequest({
  baseUrl: userUrl,
  withCredentials: true,
})